<!-- 投诉管理 -->
<template>
    <div class="complaint-container mx-5 mt-3">
        <!-- 筛选区域 -->
        <div class="mb-4 flex items-center">
            <el-radio-group v-model="filterStatus" @change="handleFilterChange">
                <el-radio-button :value="'all'">全部投诉</el-radio-button>
                <el-radio-button :value="'pending'">未处理投诉</el-radio-button>
                <el-radio-button :value="'handled'">已处理投诉</el-radio-button>
            </el-radio-group>
        </div>
        
        <!-- 投诉列表 -->
        <el-table 
            :data="filteredList" 
            style="width: 100%" 
            v-loading="loading"
            :header-cell-style="{ background: '#f5f7fa' }"
            border
        >
            <el-table-column prop="id" label="投诉编号" width="120" />
            <el-table-column prop="username" label="用户名称" width="120" />
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column prop="content" label="投诉内容" min-width="300">
                <template #default="scope">
                    <div class="content-cell">
                        <div class="content-wrapper">
                            <span class="content-text" :class="{ 'truncate': isContentOverflow(scope.row.content) }">
                                {{ scope.row.content }}
                            </span>
                            <el-button 
                                v-if="isContentOverflow(scope.row.content)"
                                type="primary" 
                                link 
                                @click="showContent(scope.row)"
                                class="detail-button"
                            >
                                查看详情
                            </el-button>
                        </div>
                        <div v-if="scope.row.reply" class="reply-content">
                            <span class="reply-label">回复：</span>
                            <span class="reply-text" :class="{ 'truncate': isContentOverflow(scope.row.reply) }">
                                {{ scope.row.reply }}
                            </span>
                            <el-button 
                                v-if="isContentOverflow(scope.row.reply)"
                                type="primary" 
                                link 
                                @click="showContent(scope.row)"
                                class="detail-button"
                            >
                                查看详情
                            </el-button>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="投诉时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '已处理' ? 'success' : 'warning'">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                    <el-button 
                        type="primary" 
                        link 
                        @click="handleReply(scope.row)"
                        :disabled="scope.row.status === '已处理'"
                    >
                        回复
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="flex justify-end mt-4">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 回复对话框 -->
        <el-dialog
            v-model="dialogVisible"
            title="回复投诉"
            width="500px"
        >
            <div class="mb-4">
                <div class="font-bold mb-2">投诉内容：</div>
                <div class="bg-gray-50 p-3 rounded">{{ currentComplaint?.content }}</div>
            </div>
            <div class="quick-reply mb-4">
                <div class="font-bold mb-2">常用语：</div>
                <div class="quick-reply-list">
                    <el-button 
                        v-for="(item, index) in quickReplies" 
                        :key="index"
                        @click="useQuickReply(item)"
                        size="small"
                    >
                        {{ item.label }}
                    </el-button>
                </div>
            </div>
            <el-form :model="replyForm" ref="replyFormRef">
                <el-form-item 
                    label="回复内容" 
                    prop="replyContent"
                    :rules="[
                        { required: true, message: '请输入回复内容', trigger: 'blur' },
                        { min: 5, message: '回复内容不能少于5个字符', trigger: 'blur' }
                    ]"
                >
                    <el-input
                        v-model="replyForm.replyContent"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入回复内容"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitReply">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 查看详情对话框 -->
        <el-dialog
            v-model="contentDialogVisible"
            title="投诉详情"
            width="500px"
        >
            <div class="mb-4">
                <div class="text-gray-500 mb-2">投诉时间：{{ currentComplaint?.createTime }}</div>
                <div class="text-gray-500 mb-4">订单编号：{{ currentComplaint?.orderNo }}</div>
                <div class="font-bold mb-2">投诉内容：</div>
                <div class="bg-gray-50 p-3 rounded whitespace-pre-wrap">{{ currentComplaint?.content }}</div>
                <template v-if="currentComplaint?.reply">
                    <div class="font-bold mb-2 mt-4">回复内容：</div>
                    <div class="bg-gray-50 p-3 rounded whitespace-pre-wrap">{{ currentComplaint?.reply }}</div>
                    <div class="text-gray-500 mt-2">回复时间：{{ currentComplaint?.replyTime }}</div>
                </template>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import instance from '@/api'

interface ComplaintItem {
    id: number
    userName: string
    orderNo: string
    content: string
    createTime: string
    status: string
    reply?: string
    replyTime?: string
}

const mockData: ComplaintItem[] = []

// 筛选状态
const filterStatus = ref('all')

// 列表数据
const complaintList = ref<ComplaintItem[]>(mockData)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(mockData.length)

// 筛选后的列表
const filteredList = computed(() => {
    if (filterStatus.value === 'all') return complaintList.value
    return complaintList.value.filter(item => 
        filterStatus.value === 'handled' ? item.status === '已处理' : item.status === '未处理'
    )
})

// 回复相关
const dialogVisible = ref(false)
const contentDialogVisible = ref(false)
const currentComplaint = ref<ComplaintItem | null>(null)
const replyForm = ref({
    replyContent: ''
})
const replyFormRef = ref<FormInstance>()

// 常用回复语
const quickReplies = [
    {
        label: '道歉',
        content: '非常抱歉给您带来不便，'
    },
    {
        label: '服务延误',
        content: '关于服务延误的问题，我们深表歉意。我们已经要求服务人员必须提前与客户沟通可能的延误情况。作为补偿，我们将为您的下一单提供9折优惠。'
    },
    {
        label: '服务态度',
        content: '对于服务人员的态度问题，我们深表歉意。我们已对相关人员进行批评教育并安排专门培训，确保此类问题不再发生。'
    },
    {
        label: '物品损坏',
        content: '对于您物品的损坏，我们深表歉意。我们将全额赔偿损失，并已对服务人员进行安全培训，以防止类似事件再次发生。'
    },
    {
        label: '服务质量',
        content: '感谢您的反馈，对于服务质量不达标的问题，我们深表歉意。我们将安排重新服务，并确保服务质量符合标准。'
    },
    {
        label: '联系方式',
        content: '如有任何问题，请随时拨打我们的客服热线：400-XXX-XXXX，我们将竭诚为您服务。'
    }
]

// 使用常用语
const useQuickReply = (reply: { label: string, content: string }) => {
    if (!replyForm.value.replyContent) {
        replyForm.value.replyContent = reply.content
    } else {
        replyForm.value.replyContent += '\n' + reply.content
    }
}

// 筛选处理
const handleFilterChange = (value: string | number | boolean | undefined) => {
    if (typeof value === 'string') {
        currentPage.value = 1
    }
}

// 分页处理
const handleSizeChange = (val: number) => {
    pageSize.value = val
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
}

// 回复处理
const handleReply = (row: ComplaintItem) => {
    currentComplaint.value = row
    dialogVisible.value = true
    replyForm.value.replyContent = ''
}

// 查看详情
const showContent = (row: ComplaintItem) => {
    currentComplaint.value = row
    contentDialogVisible.value = true
}

const submitReply = async () => {
    if (!replyFormRef.value) return
    
    await replyFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const response = await instance.post('/api/complaint/reply', {
                    complaintId: currentComplaint.value?.id,
                    replyContent: replyForm.value.replyContent
                })
                if (response.status === 200) {
                    ElMessage.success('回复成功')
                    dialogVisible.value = false
                    // 刷新列表数据
                    getComplaintList()
                } else {
                    ElMessage.error(response.data.message || '回复失败')
                }
            } catch (error) {
                ElMessage.error('回复失败，请稍后重试')
            }
        }
    })
}

// 获取投诉列表
const getComplaintList = async () => {
    loading.value = true
    try {
        const response = await instance.get('/api/complaint/list', {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value
            }
        })
        complaintList.value = response.data.list
        total.value = response.data.total
    } catch (error) {
        ElMessage.error('获取投诉列表失败')
    } finally {
        loading.value = false
    }
}

// 内容溢出检测
const isContentOverflow = (content: string) => {
    // 超过60个字符判定为溢出
    const maxLength = 60;
    return content.length > maxLength;
}

onMounted(() => {
    getComplaintList()
})
</script>

<style scoped>
.complaint-container {
    background-color: white;
    padding: 20px;
    border-radius: 4px;
}

.content-cell {
    width: 100%;
}

.content-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
}

.content-text {
    flex: 1;
    line-height: 1.5;
}

.content-text.truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.detail-button {
    flex-shrink: 0;
    padding: 0;
    height: 22px;
}

.reply-content {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px dashed #e0e0e0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.reply-label {
    color: #909399;
    flex-shrink: 0;
}

.reply-text {
    flex: 1;
    color: #67C23A;
}

.reply-text.truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.quick-reply-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.quick-reply-list .el-button {
    margin: 0;
}
</style>